
import 'dart:io';
import 'dart:typed_data';
import 'dart:convert' as convert;

import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/config.dart';
import 'package:flutter_app/widget/Image_edit.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_app/widget/Utils.dart';
import 'package:flutter_share_me/flutter_share_me.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:permission_handler/permission_handler.dart';


class Picture extends StatelessWidget {

  final String title;
  final Image img;
  final Map data;

  final MethodChannel channel = const MethodChannel('flutter_share_me');

  Picture({Key key, @required this.title, @required this.img, @required this.data}):super(key: key);

  @override
  Widget build(BuildContext context) {
    String imgTitle = data['title'] ?? "no title";
    String content = data['content'] ?? "no description";
    double size = (data['size'] ?? 0) / 1024.0;

    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.share),
            onPressed: () {
              shareImage(img.image);
            },
          ),
          IconButton(
            icon: Icon(Icons.file_download),
            onPressed: () {
              saveImage(img.image);
            },
          ),
        ],
      ),
      body: Stack(
        children: <Widget>[
          InkWell(
            child: img,
            onTap: () => Navigator.of(context).pop(),
            onLongPress: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return EditImageInfo(
                  img: Image(
                    image: CachedNetworkImageProvider("${Config.apiHost}/${data["url"]}"),
                  ),
                  data: data,
                );
              }));
            },
          ),
          Align(
            child: Container(
              padding: EdgeInsets.all(20),
              child: Text(
                imgTitle,
                style: Theme.of(context).textTheme.title,
              ),
            ),
            alignment: Alignment.topCenter,
          ),
          Align(
            child: Container(
              padding: EdgeInsets.all(20),
              child: Text(" ${size.toStringAsFixed(2)} KB"),
            ),
            alignment: Alignment.topRight,
          ),
          Align(
            child: Container(
              padding: EdgeInsets.all(20),
              child: Text(
                content,
                style: Theme.of(context).textTheme.body1,
              ),
            ),
            alignment: Alignment.bottomCenter,
          ),
        ],
        alignment: Alignment.center,
      ),
    );
  }

  saveImage(CachedNetworkImageProvider provider) async {
    // 检查并请求权限
    PermissionStatus status = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    if (PermissionStatus.granted != status) {
      PermissionHandler().requestPermissions(<PermissionGroup>[
        PermissionGroup.storage,
      ]);
    }

    DefaultCacheManager mngr = provider.cacheManager ?? DefaultCacheManager();
    String url = provider.url;
    Map<String, String> headers = provider.headers;
    File file = await mngr.getSingleFile(url, headers: headers);
//    Uint8List uint8list = await file.readAsBytes();
//    final result = await ImageGallerySaver.saveImage(uint8list);
    final result = await ImageGallerySaver.saveFile(file.path);
    if(result != null && result != "") {
      String str = Uri.decodeComponent(result);
      Utils.showToast("成功保存到$str");
    } else {
      Utils.showToast("保存失败");
    }
  }

  shareImage(CachedNetworkImageProvider provider) async {

    await saveImage(provider);

    dynamic result;
    try {
      result = await channel.invokeMethod('system', {"msg": "分享自 http://jvm123.com"});
      Utils.showToast("图片已经保存，请在应用内选择进行分享！");
    } catch (e) {
      Utils.showToast("分享失败！");
    }
  }

}